package cn.com.xinjinfu.pdoulcProduct.activity.login;

import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseWebActivity;
import cn.com.xinjinfu.pdoulcProduct.activity.user.ActCertification;
import cn.com.xinjinfu.pdoulcProduct.engine.ComAsk;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.manager.ActivityManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.NewUtil;

/**
 * 注册
 *
 * @author zqm
 */
public class RegisterActivity extends BaseActivity implements OnClickListener, View.OnFocusChangeListener {
    private RequestQueue requen;
    private Button btcode;
    private TextView tvxieyi;
    private TextView tvxieyi2;
    private LinearLayout ll_yaoqing_view;
    private CheckBox get_yaoqingnum, cb;
    private EditText etpw, etpw2, etcode, etyaoqing;
    private String passwd, passwd1, code, yaoqingcode;
    private Button register_register_bt;
    private Dialog dialog;
    private TextView tv_error_hint01, tv_error_hint02, tv_error_hint03;
    private TextView tv_mobile;
    private ImageView iv_selector;
    private String mobile;
    private int x, y, z;
    private Dialog dg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_register);
        TitleManager.showTitle(this, "注册", "");
        ActivityManager.getInstance().addActivity(this);
        Intent intent = getIntent();
        mobile = intent.getStringExtra("mobile"); //取得手机号
        intiViews();
        requen = Volley.newRequestQueue(this);
    }


    protected void intiViews() {
        tv_mobile = (TextView) findViewById(R.id.tv_mobile);
        tv_mobile.setText(mobile.substring(0, 3) + "****" + mobile.substring(7));
        tv_error_hint01 = (TextView) findViewById(R.id.tv_error_hint01);
        tv_error_hint02 = (TextView) findViewById(R.id.tv_error_hint02);
        tv_error_hint03 = (TextView) findViewById(R.id.tv_error_hint03);
        //如何获取邀请码弹窗
        ll_yaoqing_view = (LinearLayout) findViewById(R.id.ll_yaoqing_view);
        get_yaoqingnum = (CheckBox) findViewById(R.id.get_yaoqingnum);
        get_yaoqingnum.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    ll_yaoqing_view.setVisibility(View.GONE);
                } else {
                    ll_yaoqing_view.setVisibility(View.VISIBLE);
                }
            }
        });
        get_yaoqingnum.setChecked(false);

        etpw = (EditText) findViewById(R.id.et_pw);
        etpw2 = (EditText) findViewById(R.id.et_pw2);
        etcode = (EditText) findViewById(R.id.et_code);//验证码
        etyaoqing = (EditText) findViewById(R.id.et_yaoqing);//邀请码
        etcode.setOnFocusChangeListener(this);
        etpw.setOnFocusChangeListener(this);
        etpw.addTextChangedListener(mTextWatcher);
        etpw2.addTextChangedListener(mTextWatcher);
        etcode.addTextChangedListener(mTextWatcher);

        btcode = (Button) findViewById(R.id.bt_code);  //获得验证码
        GradientDrawable myGrad = (GradientDrawable)btcode.getBackground();
        myGrad.setColor(0xFF6ED3D6);
        btcode.setOnClickListener(this);

        iv_selector = (ImageView) findViewById(R.id.iv_selector);
        tvxieyi = (TextView) findViewById(R.id.tv_xieyi);
        tvxieyi2 = (TextView) findViewById(R.id.tv_xieyi2);
        tvxieyi.setOnClickListener(this);
        tvxieyi2.setOnClickListener(this);
        register_register_bt = (Button) findViewById(R.id.register_register_bt);
        register_register_bt.setOnClickListener(this);

        cb = (CheckBox) findViewById(R.id.cb);
        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    iv_selector.setImageResource(R.drawable.btn_ok);
                    if (x == 1 && y == 1 && z == 1) {
                        register_register_bt.setEnabled(true);
                    } else {
                        register_register_bt.setEnabled(false);
                    }
                } else {
                    iv_selector.setImageResource(R.drawable.btn_no);
                    register_register_bt.setEnabled(false);
                }
            }
        });
        cb.setChecked(true);

    }

    public void onClick(View v) {
        if (!NewUtil.checkClick(v.getId())) return;
        String url = DataHandler.WEBURL + "/front/wa/serviceAgreement?pactId=11";
        Intent intent = new Intent(this, BaseWebActivity.class);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.bt_code:
                //获得验证码
                ComAsk.getVerifyCode(mobile, this, btcode, "1");
                break;
            case R.id.register_register_bt:
                loginRequen();
                break;
            case R.id.tv_xieyi:
                bundle.putString("url", url);
                bundle.putString("title", "服务协议");
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.tv_xieyi2:
                url = DataHandler.WEBURL + "/front/wa/serviceAgreement?pactId=13";
                bundle.putString("url", url);
                bundle.putString("title", "借款协议");
                intent.putExtras(bundle);
                startActivity(intent);
                break;
        }
    }

    public void loginRequen() {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        yaoqingcode = etyaoqing.getText().toString()+"";
        final Map<String, String> parameters = DataHandler.getParameters("1001");
        code = etcode.getText().toString();
        parameters.put("code", code);
        parameters.put("invitationCode", yaoqingcode);
        parameters.put("mobile", mobile);
        parameters.put("passwd", DataHandler.encrypt3DES(passwd));
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
        requen.add(request);
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(RegisterActivity.this, error);
        }
    };

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.i("注册结果" + jobj.toString());
            dg.dismiss();
            if(JSONManager.getError(jobj) == -1){
                ToastManager.showShort(RegisterActivity.this,JSONManager.getMsg(jobj));          //提示注册成功
                //跳转到实名认证
                Intent intent = new Intent();
                intent.putExtra("id", JSONManager.getString(jobj,"id"));
                intent.putExtra("mobile", mobile);
                intent.putExtra("pwd", passwd);
                intent.setClass(RegisterActivity.this, ActCertification.class);
                startActivity(intent);
            } else {
                tv_error_hint03.setVisibility(View.VISIBLE);
                tv_error_hint03.setText(JSONManager.getMsg(jobj));  //提示注册失败提示
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().removeActivity(this);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.et_code:
                if (!hasFocus) {
                    code = etcode.getText().toString();
                    if (!code.equals("")) {
                        if (code.length() != 4) {
                            tv_error_hint01.setVisibility(View.VISIBLE);
                            tv_error_hint01.setText("验证码错误，请重新输入");
                            x = 0;
                        } else {
                            tv_error_hint01.setVisibility(View.GONE);
                            x = 1;
                        }
                    } else {
                        tv_error_hint01.setVisibility(View.GONE);
                        x = 0;
                    }
                }
                break;
            case R.id.et_pw:
                if (!hasFocus) {
                    passwd = etpw.getText().toString();
                    if (!passwd.equals("")) {
                        if (passwd.length() > 12 || passwd.length() < 6) {
                            tv_error_hint02.setVisibility(View.VISIBLE);
                            tv_error_hint02.setText("密码长度应为6-12位字符");
                            y = 0;
                        } else {
                            tv_error_hint02.setVisibility(View.GONE);
                            y = 1;
                        }
                    } else {
                        tv_error_hint02.setVisibility(View.GONE);
                        y = 0;
                    }
                }
                break;

        }
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            passwd1 = etpw2.getText().toString();
            passwd = etpw.getText().toString();
            if (!passwd1.equals("")) {
                if (!passwd.equals(passwd1)) {
                    tv_error_hint02.setVisibility(View.VISIBLE);
                    tv_error_hint02.setText("两次密码不一致");
                    z = 0;
                    register_register_bt.setEnabled(false);
                } else {
                    tv_error_hint02.setVisibility(View.GONE);
                    z = 1;
                    if (cb.isChecked() && !TextUtils.isEmpty(etcode.getText())) {
                        register_register_bt.setEnabled(true);
                    }else {
                        register_register_bt.setEnabled(false);
                    }
                }
            } else {
                tv_error_hint02.setVisibility(View.GONE);
                z = 0;
                register_register_bt.setEnabled(false);
            }
        }
    };
}